//! the item1 menu.

use bevy::{prelude::*, ecs::spawn::SpawnIter, ui::Val::*, input::common_conditions::input_just_pressed,};

use crate::{asset_tracking::LoadResource, audio::music, menus::Menu, theme::prelude::*};

pub(super) fn plugin(app: &mut App){
    // 点击进入，则启动
    app.add_systems(OnEnter(Menu::Item1), spawn_item1_page);

    // 当前页面,点击esc则后退
    app.add_systems(
        Update,
        go_back.run_if(in_state(Menu::Item1).and(input_just_pressed(KeyCode::Escape)))
    );

    // 注册资源，读取资源，使用资源
    app.register_type::<Item1Assets>();
    app.load_resource::<Item1Assets>();
    app.add_systems(OnEnter(Menu::Item1), start_item1_music);
}

fn spawn_item1_page(mut commands: Commands){
    commands.spawn((
        widget::ui_root("item1 page"),
        GlobalZIndex(2),
        StateScoped(Menu::Item1),
        children![
            widget::header("Item1 header"),
            after_hearder(),
            widget::header("Item1 body"),
            after_body(),
            widget::button("Back", go_back_on_click),
        ],
    ));
}

fn after_hearder() -> impl Bundle{
    grid(
        vec![
            ["row 1, clo 1", "row 1 clo 2"],
            ["row 2, clo 1", "row 2 clo 2"],
        ]
    )
}

fn after_body() -> impl Bundle{
    grid(
        vec![
            ["row 11, clo 1", "row 11 clo 2"],
            ["row 12, clo 1", "row 12 clo 2"],
        ]
    )
}

fn grid(content: Vec<[&'static str; 2]>) -> impl Bundle{
    (
        Name::new("Grid"),
        Node{
            display: Display::Grid,
            row_gap: Px(10.0),
            column_gap: Px(30.0),
            grid_template_columns: RepeatedGridTrack::px(2, 400.0),
            ..default()
        },
        Children::spawn(SpawnIter(content.into_iter().flatten()
            .enumerate().map(|(i, text)| {
                (
                    widget::label(text),
                    Node{
                        justify_self: if i.is_multiple_of(2) {
                            JustifySelf::End
                        } else {
                            JustifySelf::Start
                        },
                        ..default()
                    }
                )
            }))),
    )
}

fn go_back_on_click(_: Trigger<Pointer<Click>>, mut next_menu: ResMut<NextState<Menu>>){
    next_menu.set(Menu::Main);
}

fn go_back(mut next_menu: ResMut<NextState<Menu>>){
    next_menu.set(Menu::Main);
}


#[derive(Resource, Asset, Clone, Reflect)]
#[reflect(Resource)]
struct Item1Assets{
    #[dependency]
    music: Handle<AudioSource>,
}

impl FromWorld for Item1Assets {
    fn from_world(world: &mut World) -> Self {
        let assets = world.resource::<AssetServer>();
        Self {
            music: assets.load("audio/music/Monkeys Spinning Monkeys.ogg"),
        }
    }
}

fn start_item1_music(mut command: Commands, item1_music: Res<Item1Assets>){
    command.spawn((
        Name::new("item1 musice"),
        StateScoped(Menu::Item1),
        music(item1_music.music.clone()),
    ));
}
